﻿using IPTVRClient.common;
using IPTVRClient.dao;
using IPTVRClient.model;
using IPVTRClient.Properties;
using IPTVRClient.service;
using IPTVRClient.Utils;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using IPVTRClient.views;
using IPTVRClient.Common;
using IPVTRClient.service;

namespace IPTVRClient.views
{
    public partial class CameraVideoForm : Form
    {
        Sunisoft.IrisSkin.SkinEngine skin = new Sunisoft.IrisSkin.SkinEngine();
        private string pluginPath = Environment.CurrentDirectory + "\\plugins\\";  //插件目录

        private CameraVideoService cameraVideoService = new CameraVideoService();

        ILog m_log = LogManager.GetLogger("CameraVideoForm");

        private bool isLocked = false;

        private int screen;

        public CameraVideoForm()
        {
            InitializeComponent();

            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);

            //开启双缓冲
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
        }

        private int curScreenNum = 0;
        private bool isFullScreen = false;
        private bool isMute = false;
        private int row = 0;
        private int col = 0;
        private bool isBottomFullScreen = false;

        // 视频显示窗口
        private Panel[] pb = new Panel[64];

        // 视频显示窗口下方的控制区
        private Panel[] videoControlPanel = new Panel[64];

        // 视频显示区域
        private Panel[] videoPanel = new Panel[64];

        // 视屏操作控制区域
        private Panel[] ctrPanel = new Panel[64];

        // 设备名称显示
        private Label[] deviceNameLabel = new Label[64];

        // 静音操作按钮
        private PictureBox[] pbMute = new PictureBox[64];

        // 全屏操作按钮
        private PictureBox[] pbFullScreen = new PictureBox[64];

        // 播放器
        private VlcPlayer[] vlcPlayer = new VlcPlayer[64];

        //播放被叫，主叫声音
        private VlcPlayer vlcAudioPlayer0 = null;
        private VlcPlayer vlcAudioPlayer1 = null;

        // 设备列表
        private List<Device> devList = new List<Device>();
        
        private int devTotal;

        private int TimeCount = 0;

        public int DevTotal
        {
            get { return devTotal; }
            set { devTotal = value; }
        }

        private int currentPage = 1;

        public int CurrentPage
        {
            get { return currentPage; }
            set { currentPage = value; }
        }

        private int totalPage;

        public int TotalPage
        {
            get { return totalPage; }
            set { totalPage = value; }
        }

        // 记录当前播放哪个监控的声音
        private int audioInddex = -1;

        public int AudioIndex
        {
            get { return audioInddex; }
            set { audioInddex = value; }
        }

        /// <summary>
        /// 分屏实现
        /// </summary>
        /// <param name="num"></param>
        private void split_screen(int num)
        {
            try
            {
                // 清除之前的界面
                tlp_screen.ColumnStyles.Clear();
                tlp_screen.RowStyles.Clear(); // 清除行列属性  
                int i;
                for (i = 0; i < curScreenNum; i++)
                {
                    tlp_screen.Controls.Remove(videoControlPanel[i]);
                }
                tlp_screen.Refresh();

                int Sqrt_num = (int)Math.Sqrt(num);
                tlp_screen.ColumnCount = Sqrt_num;
                tlp_screen.RowCount = Sqrt_num;
                float style = 100 / Sqrt_num;

                for (int j = 0; j < Sqrt_num; j++)
                {
                    tlp_screen.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
                }

                for (int j = 0; j < Sqrt_num; j++)
                {
                    tlp_screen.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
                }
                //tlp_screen.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, style));
                //tlp_screen.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, style));
                int pb_width = (tlp_screen.Width - 6 * Sqrt_num) / Sqrt_num; // 无法修改picturebox的Margin为0(默认为3)，所以可设置空格6*列/行  
                int pb_height = (tlp_screen.Height - 6 * Sqrt_num) / Sqrt_num;
                for (i = 0; i < num; i++)
                {
                    row = i / Sqrt_num;
                    col = i % Sqrt_num;

                    // 视频操作总区域
                    videoControlPanel[i] = new Panel();
                    videoControlPanel[i].Tag = i;

                    // 监控显示区域
                    pb[i] = new Panel();
                    pb[i].Tag = i;
                    //pb[i].Click += new System.EventHandler(this.PicClick);
                    videoControlPanel[i].Controls.Add(pb[i]);
                    pb[i].BackColor = Color.DarkGray;
                    pb[i].Size = new System.Drawing.Size(pb_width, pb_height - 15);

                    // 监控操作面板
                    ctrPanel[i] = new Panel();
                    ctrPanel[i].Tag = i;

                    // 设备名称label
                    deviceNameLabel[i] = new Label();
                    deviceNameLabel[i].Text = "未知";
                    deviceNameLabel[i].Dock = DockStyle.Left;
                    deviceNameLabel[i].Tag = i;
                    ctrPanel[i].Controls.Add(deviceNameLabel[i]);

                    // 静音按钮
                    pbMute[i] = new PictureBox();
                    pbMute[i].Tag = i;
                    Image backImage = Resources.sound_mute;
                    pbMute[i].Image = backImage;
                    pbMute[i].Location = new System.Drawing.Point(ctrPanel[i].Location.X + ctrPanel[i].Width - 15, ctrPanel[i].Location.Y);
                    pbMute[i].Size = new System.Drawing.Size(15, 15);
                    pbMute[i].Dock = DockStyle.Right;

                    // 鼠标点击事件
                    pbMute[i].Click += new System.EventHandler(this.PicMuteClick);
                    pbMute[i].Enabled = false;
                    ctrPanel[i].Controls.Add(pbMute[i]);

                    // 全屏按钮
                    pbFullScreen[i] = new PictureBox();
                    pbFullScreen[i].Tag = i;
                    backImage = Resources.fullscreen_alt;
                    pbFullScreen[i].Image = backImage;
                    pbFullScreen[i].Dock = DockStyle.Right;
                    pbFullScreen[i].Location = new System.Drawing.Point(ctrPanel[i].Location.X + ctrPanel[i].Width - 10, ctrPanel[i].Location.Y);
                    pbFullScreen[i].Size = new System.Drawing.Size(15, 15);

                    // 鼠标点击事件
                    pbFullScreen[i].Click += new System.EventHandler(this.PicClick);
                    pbFullScreen[i].Enabled = false;
                    ctrPanel[i].Controls.Add(pbFullScreen[i]);

                    videoControlPanel[i].Controls.Add(ctrPanel[i]);
                    ctrPanel[i].BackColor = Color.LightGray;
                    ctrPanel[i].Dock = DockStyle.Bottom;
                    ctrPanel[i].Size = new System.Drawing.Size(pb_width, 15);

                    // 监控和控制区域
                    tlp_screen.Controls.Add(videoControlPanel[i], col, row);
                    videoControlPanel[i].BackColor = Color.Transparent;
                    //videoControlPanel[i].Dock = DockStyle.Fill;
                    videoControlPanel[i].Location = new System.Drawing.Point(row * pb_width, col * pb_height);
                    videoControlPanel[i].Size = new System.Drawing.Size(pb_width, pb_height);
                    //Point_Old = new System.Drawing.Point(pb_width, pb_height);
                }
                curScreenNum = num;
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        
      /// <summary>
      /// 初始化设备监控面板
      /// </summary>
      /// <param name="para">查询参数，设备id或者设备别名</param>
      /// <param name="start">查询起始数目</param>
      /// <param name="limit">每页大小</param>
        private  void InitDevCameraPanel(string para, int start, int limit)
        {
            try
            {
                // 根据条件查询设备列表，如果条件为空，则表示查询所有
                DataSet ds = cameraVideoService.GetAllDevice(para, start, limit);

                List<Device> devList = Global.TableToEntity<Device>(ds.Tables[0]);

                if (0 == this.DevTotal && devList.Count == 0)
                {
                    return;
                }

                if(0 == this.DevTotal)
                {
                    this.DevTotal = cameraVideoService.GetDeviceCount(para);
                }

                int size = devList.Count;

                // 遍历设备列表
                for (int i = 0; i < screen; i++)
                {
                    if (i < size)
                    {
                        AddDeviceToVideoPanel(i, devList[i]);
                    }
                    else
                    {
                        deviceNameLabel[i].Text = "未知";
                    }
                }

                lblInfo.Text = "设备总数:" + this.DevTotal.ToString() + "个,共" + this.TotalPage.ToString() + "页,当前第" + this.CurrentPage.ToString() + "页";
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 计算总页数
        /// </summary>
        /// <param name="total"></param>
        /// <returns></returns>
        private void GetTotalPage(int total, int screenNum)
        {
            // 计算总页数
            this.TotalPage = this.DevTotal / screenNum;

            if (this.DevTotal % screenNum != 0)
            {
                this.TotalPage = this.DevTotal / screenNum + 1;
            }
        }

        /// <summary>
        /// 静音按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PicMuteClick(object sender, EventArgs e)
        {
            try
            {
                //根据tag值找出设备id
                PictureBox pic = sender as PictureBox;
                int index = Convert.ToInt32(pic.Tag);
                m_log.Debug("mute operation:  index is: " + index);
                Image backImage = Resources.sound_volume;

                Device dev = Global.GetDevice(index);
                if (dev != null && dev.Devid != null)
                {
                    string para = "";

                    // 相等表示关闭该设备的音频
                    if (this.AudioIndex == index)
                    {
                        // 关闭音频流，设备id为空
                        para = "{\"devid\":\"" + "" + "\"}";
                    }
                    else
                    {
                        para = "{\"devid\":\"" + dev.Devid + "\"}";
                    }

                    string url = "http://" + Global.configParam.Ipaddr + ":" + Global.configParam.Port + "/openaudio";

                    string response = Global.HttpPost(url, para);
                    m_log.Debug("set device " + dev.Devid + " audio and result is:" + response);
                    JObject jo = (JObject)JsonConvert.DeserializeObject(response);

                    string result = jo["errCode"].ToString();

                    if (result.Equals("0"))
                    {
                        // 音频关闭成功，更换图标
                        if (this.AudioIndex == index)
                        {
                            backImage = Resources.sound_mute;
                            pbMute[AudioIndex].Image = backImage;
                            this.AudioIndex = -1;
                            vlcAudioPlayer0.Stop();
                            vlcAudioPlayer1.Stop();
                        }
                        else // 开启音频
                        {
                            string[] strArray = dev.Audiowatchaddr.Split(':');
                            vlcAudioPlayer0.LoadOnlineFile("udp://@:" + strArray[1]);
                            vlcAudioPlayer1.LoadOnlineFile("udp://@:" + (int.Parse(strArray[1])+1).ToString());


                            // 将上次非静音图表变更为静音
                            if (this.AudioIndex > -1)
                            {
                                backImage = Resources.sound_mute;
                                pbMute[AudioIndex].Image = backImage;
                            }
                            this.AudioIndex = index;

                            // 将该区域的监控静音图标
                            backImage = Resources.sound_volume;
                            pbMute[index].Image = backImage;
                        }
                    }
                    else
                    {
                        Global.showAlertBox("操作失败");
                    }
                }
            }
            catch 

            {
                Global.showAlertBox("操作失败");
            }
        }

        /// <summary>
        /// 视屏窗口点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PicClick(object sender, EventArgs e)
        {
            try
            {
                PictureBox pic = sender as PictureBox;
                int index = Convert.ToInt32(pic.Tag);
                FullScreen(pic, index);
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 全屏功能实现
        /// </summary>
        /// <param name="pic"></param>
        private void FullScreen(PictureBox pic, int index)
        {
            /*窗体外全屏*/
            if (!isFullScreen)
            { //Full Screen  
                isFullScreen = true;
                //this.FormBorderStyle = FormBorderStyle.None; //取消窗体边框  
                plCenter.BringToFront();
                this.videoControlPanel[index].Parent = plCenter;
                this.videoControlPanel[index].Dock = DockStyle.Fill;
                pb[index].Dock = DockStyle.Fill;
                tlp_screen.Hide();
                plCenter.Show();
                cbxScreenPage.Enabled = false;
            }
            else
            {
                //Cancel Full Screen  
                isFullScreen = false;
                tlp_screen.BringToFront();
                this.videoControlPanel[index].Parent = tlp_screen;
                this.videoControlPanel[index].Dock = DockStyle.Fill;
                tlp_screen.Show();
                cbxScreenPage.Enabled = true;
            }
        }

        /// <summary>
        /// form 表单加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CameraVideoForm_Load(object sender, EventArgs e)
        {
            Image backImage = Resources._lock;
            pbLock.Image = backImage;

            if (Global.CurrentUser.RealName.Length > 0)
            {
                lblWelcome.Text = "欢迎 " + Global.CurrentUser.RealName + " 登录！";
            }
            else
            {
                lblWelcome.Text = "欢迎 " + Global.CurrentUser.LoginId + " 登录！";
            }

            timerTimeInfo.Start();
            string time = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            lblTime.Text = time;

            screen = Global.configParam.ScreenNum;
            cbxScreenPage.SelectedIndex = Global.SplitScreenNumToIndex(screen);

            // 初始化设备列表
            Bind_DeviceTreeView(treeDevice);

            // 初始化逻辑分组列表
            Bind_GroupTreeView(treeGroup);
            // 音频播放器
            vlcAudioPlayer0 = new VlcPlayer(pluginPath, false);
            vlcAudioPlayer0.SetRenderWindow((int)plAudio.Handle);

            vlcAudioPlayer1 = new VlcPlayer(pluginPath, false);
            vlcAudioPlayer1.SetRenderWindow((int)plAudio.Handle);
        }

        /// <summary>
        /// 设置双缓冲，防止界面闪烁
        /// </summary>
        /// <param name="cc"></param>
        public static void SetDouble(Control cc)
        {
            cc.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance |
                         System.Reflection.BindingFlags.NonPublic).SetValue(cc, true, null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CameraVideoForm_SizeChanged(object sender, EventArgs e)
        {
            
        }

        /// <summary>
        /// 解决动态创建面板界面闪烁问题
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }


        /// <summary>
        /// 逻辑分组树形结构右键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeGroup_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Right)
                {
                    Point p = new Point(e.X, e.Y);

                    TreeNode CurrentNode = treeGroup.GetNodeAt(p);
                    if (CurrentNode != null)
                    {
                        CurrentNode.ContextMenuStrip = this.ctxMenuGroup;
                        treeGroup.SelectedNode = CurrentNode;
                    }
                }
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 初始化设备列表根节点
        /// </summary>
        /// <param name="treeView"> treeview 控件id</param>
        private void Bind_DeviceTreeView(TreeView treeView)
        {
            DataSet ds = new DataSet();
            ds = cameraVideoService.GetDeviceLevelNode(0);
            treeView.Nodes.Clear();

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                TreeNode rootnode = new TreeNode();
                rootnode.Tag = ds.Tables[0].Rows[i][0].ToString();
                rootnode.Name = "group";
                rootnode.ImageIndex = 1;
                rootnode.SelectedImageIndex = 1;
                rootnode.Text = ds.Tables[0].Rows[i][3].ToString();
                treeView.Nodes.Add(rootnode);

                CreateChildNodes(rootnode, Convert.ToInt32(ds.Tables[0].Rows[i][0]));
            }

            // 默认展开所有
            treeView.ExpandAll();
        }

        /// <summary>
        /// 初始化设备列表根节点
        /// </summary>
        /// <param name="treeView"> treeview 控件id</param>
        private void Bind_GroupTreeView(TreeView treeView)
        {
            DataSet ds = new DataSet();
            ds = cameraVideoService.GetDeviceLevelNode(0);
            treeView.Nodes.Clear();

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                TreeNode rootnode = new TreeNode();
                rootnode.Tag = ds.Tables[0].Rows[i][0].ToString();
                rootnode.Name = "group";
                rootnode.ImageIndex = 1;
                rootnode.SelectedImageIndex = 1;
                rootnode.Text = ds.Tables[0].Rows[i][3].ToString();
                treeView.Nodes.Add(rootnode);

                CreateGroupChildNodes(rootnode, Convert.ToInt32(ds.Tables[0].Rows[i][0]));
            }

            // 默认展开所有
            treeView.ExpandAll();
        }


        /// <summary>
        /// 初始化二级子节点，分组
        /// </summary>
        /// <param name="treenode"></param>
        /// <param name="parentName"></param>
        /// <param name="text"></param>
        /// <param name="index"></param>
        private void CreateGroupChildNodes(TreeNode treenode, int index)
        {
            DataSet ds = new DataSet();
            ds = cameraVideoService.GetNextLevelNode(index, 1);

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                TreeNode childnode = new TreeNode();
                childnode.Tag = ds.Tables[0].Rows[i][0].ToString();
                childnode.Name = "group";
                childnode.ImageIndex = 1;
                childnode.SelectedImageIndex = 1;
                childnode.Text = ds.Tables[0].Rows[i][3].ToString();
                treenode.Nodes.Add(childnode);
            }
        }

        /// <summary>
        /// 初始化二级子节点，可能同时包含设备及分组
        /// </summary>
        /// <param name="treenode"></param>
        /// <param name="parentName"></param>
        /// <param name="text"></param>
        /// <param name="index"></param>
        private void CreateChildNodes(TreeNode treenode, int index)
        {
            // 查询根节点下面的设备
            DataSet dsDev = new DataSet();
            dsDev = cameraVideoService.GetDeviceByGroupId(index);
            for (int i = 0; i < dsDev.Tables[0].Rows.Count; i++)
            {
                TreeNode childnode = new TreeNode();
                childnode.Tag = dsDev.Tables[0].Rows[i][1].ToString();
                childnode.Text = dsDev.Tables[0].Rows[i][2].ToString();
                childnode.ImageIndex = 0;
                childnode.SelectedImageIndex = 0;
                treenode.Nodes.Add(childnode);
            }

            DataSet ds = new DataSet();
            ds = cameraVideoService.GetNextLevelNode(index, 1);

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                TreeNode childnode = new TreeNode();
                childnode.Tag = ds.Tables[0].Rows[i][0].ToString();
                childnode.Name = "group";
                childnode.ImageIndex = 1;
                childnode.SelectedImageIndex = 1;
                childnode.Text = ds.Tables[0].Rows[i][3].ToString();
                treenode.Nodes.Add(childnode);

                // 添加三级节点
                CreateGrandsonNodes(childnode, Convert.ToInt32(ds.Tables[0].Rows[i][0]));
            }
        }

        /// <summary>
        /// 三级子节点，三级节点即就是设备
        /// </summary>
        private void CreateGrandsonNodes(TreeNode treenode, int index)
        {
            // 查询根节点下面是否包含设备
            DataSet dsDev = new DataSet();
            dsDev = cameraVideoService.GetDeviceByGroupId(index);
            for (int i = 0; i < dsDev.Tables[0].Rows.Count; i++)
            {
                TreeNode childnode = new TreeNode();
                childnode.Tag = dsDev.Tables[0].Rows[i][1].ToString();
                childnode.Text = dsDev.Tables[0].Rows[i][2].ToString();
                childnode.ImageIndex = 0;
                childnode.SelectedImageIndex = 0;
                treenode.Nodes.Add(childnode);
            }
        }

        /// <summary>
        /// tab页签切换事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 选中逻辑分组页签
            if (tbControl.SelectedIndex == 1)
            {
                Bind_GroupTreeView(treeGroup);
            }

            // 选中设备列表页签
            if (tbControl.SelectedIndex == 0)
            {
                Bind_DeviceTreeView(treeDevice);
            }
        }

        /// <summary>
        /// 逻辑分组增加右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuAddGroup_Click(object sender, EventArgs e)
        {
            AddGroupForm addGroupForm = new AddGroupForm(true, "0");
            DialogResult result = addGroupForm.ShowDialog();

            // 添加成功后，是否刷新界面
            if (result == DialogResult.OK)
            {
                // 查询设备总数，根据总数决定是否显示分页按钮
                Bind_GroupTreeView(treeGroup);
            }
        }

        private void menuUpdateGroup_Click(object sender, EventArgs e)
        {
            AddGroupForm addGroupForm = new AddGroupForm(false, treeGroup.SelectedNode.Tag.ToString());
            DialogResult result = addGroupForm.ShowDialog();

            // 添加成功后，是否刷新界面
            if (result == DialogResult.OK)
            {
                // 最后关闭添加界面
                addGroupForm.Close();

                Bind_GroupTreeView(treeGroup);
            }
        }

        private void menuDelGroup_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult result = Global.showQuestionMessageBox("确定要删除该分组吗？", 2);
                if (result == DialogResult.OK)
                {
                    // 执行删除操作，先删除数据库，再从界面删除
                    string groupId = treeGroup.SelectedNode.Tag.ToString();
                    if (!cameraVideoService.IsUseGroup(groupId))
                    {
                        cameraVideoService.DeleteGroupByGroupId(groupId);
                        Bind_GroupTreeView(treeGroup);
                    }
                    else
                    {
                        MessageBox.Show("分组被使用,请先删除关联设备或者子分组。", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 设备列表树形控件  右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeDevice_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Right)
                {
                    Point p = new Point(e.X, e.Y);

                    TreeNode CurrentNode = treeDevice.GetNodeAt(p);
                    if (CurrentNode != null && CurrentNode.Name.Equals("group"))
                    {
                        CurrentNode.ContextMenuStrip = this.ctxMenuDevice;
                        treeDevice.SelectedNode = CurrentNode;
                    }
                    else
                    {
                        CurrentNode.ContextMenuStrip = this.ctxMenuDeviceMange;
                        treeDevice.SelectedNode = CurrentNode;
                    }
                }
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 设备添加右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuAddDevice_Click(object sender, EventArgs e)
        {
            AddDeviceFrom addDeviceFrom = new AddDeviceFrom(true,treeDevice.SelectedNode.Tag.ToString());
            DialogResult result = addDeviceFrom.ShowDialog();

            // 添加成功后，是否刷新界面
            if (result == DialogResult.OK)
            {
                // 最后关闭添加界面
                addDeviceFrom.Close();

                Bind_DeviceTreeView(treeDevice);

                this.DevTotal ++;

                // 计算分页
                GetTotalPage(this.DevTotal, screen);
            }
            else
            {
                // 最后关闭添加界面
                addDeviceFrom.Close();
                return;
            }

            if (this.CurrentPage == this.TotalPage)
            {
                if (this.DevTotal % Global.configParam.ScreenNum != 0)
                {
                    // 添加完设备以后，需要在右侧监控窗口显示区域进行播放
                    Device dev = addDeviceFrom.Device;

                    // 将设备信息与监控区的tag值的关系存储到map中
                    for (int i = 0; i < 64; i++)
                    {
                        // 如果不包含tag或者 tag对应的值为null 表示该位置无设备
                        if (!Global.ContainsDevice(i))
                        {
                            AddDeviceToVideoPanel(i, dev);
                            return;
                        }
                        else
                        {
                            if (Global.GetDevice(i) == null)
                            {
                                AddDeviceToVideoPanel(i, dev);
                                return;
                            }
                        }
                    }
                }
                else
                {
                    return;
                }
            }
            else if (this.CurrentPage > 1 && this.CurrentPage < this.TotalPage)
            {
                return;
            }
        }

        /// <summary>
        /// 将设备信息展示到监控面板
        /// </summary>
        /// <param name="index"></param>
        /// <param name="dev"></param>
        private void AddDeviceToVideoPanel(int index, Device dev)
        {
            Global.RemoveDevice(index);
            Global.AddDevice(index, dev);
           
            deviceNameLabel[index].Text = dev.Alias;
            pbMute[index].Enabled = true;
            pbFullScreen[index].Enabled = true;

            // 绑定vlc //不存在初始化vlc
            if (vlcPlayer[index] == null)
            {
                vlcPlayer[index] = new VlcPlayer(this.pluginPath, true);
            }
            else
            {
                vlcPlayer[index].Stop();
            }
            vlcPlayer[index].SetRenderWindow((int)pb[index].Handle);

            if (dev.Status == 2)
            {
                pb[index].BackColor = Color.Gray;
            }
            else
            {
                pb[index].BackColor = Color.Black;
            }
                        
            string []strArray = dev.Videowatchaddr.Split(':');
            if(strArray.Length == 2)
            {
                vlcPlayer[index].LoadOnlineFile("udp://@:" + strArray[1]);
            }
            else
            {
                Console.Write("add vlc fail");
            }
        }

        /// <summary>
        /// 设备信息查看，设备信息更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolMenuUpdate_Click(object sender, EventArgs e)
        {
            AddDeviceFrom addDeviceFrom = new AddDeviceFrom(false, treeDevice.SelectedNode.Tag.ToString());

            DialogResult result = addDeviceFrom.ShowDialog();

            // 添加成功后，是否刷新界面
            if (result == DialogResult.OK)
            {
                // 最后关闭添加界面
                addDeviceFrom.Close();

                Bind_DeviceTreeView(treeDevice);

                Global.ClearDevice();
                InitDevCameraPanel("", (currentPage - 1) * screen, screen);
            }
        }

        /// <summary>
        /// 删除设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tooMenuDelete_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult result = Global.showQuestionMessageBox("确定要删除该设备吗？", 2);

                if (result == DialogResult.OK)
                {
                    // 执行删除操作，先删除数据库，再从界面删除
                    string deviceId = treeDevice.SelectedNode.Tag.ToString();
                    int rt = -1;
                    rt = cameraVideoService.DeleteDeviceByDevId(deviceId);
                    if (rt > 0)
                    {
                        rt = cameraVideoService.DeleteDeviceGroupById(deviceId);
                    }
                    // 从数据库中删除，从设备与监控显示区的map中清空
                    if (rt > 0)
                    {
                        // 刷新界面
                        Bind_DeviceTreeView(treeDevice);


                        if (Global.GetDeviceCount() == 0)
                        {
                            return;
                        }

                        for (int i = 0; i < 64; i++)
                        {
                            Device dev = Global.GetDevice(i);
                            if (dev != null)
                            {
                                if (dev.Devid.Equals(deviceId))
                                {
                                    Global.RemoveDevice(i);
                                    deviceNameLabel[i].Text = "未知";
                                    vlcPlayer[i].Stop();
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 查询按钮事件，目前用于测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                Global.ClearDevice();
                InitDevCameraPanel(tbSearch.Text.Trim(), 0, screen);
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 定时更新时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerTimeInfo_Tick(object sender, EventArgs e)
        {
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            lblTime.Text = time;

            //刷新播放器状态
            if (TimeCount > 5)
            {
                refreshvlcPlay();
                TimeCount = 0;
            }
            else
            {
                TimeCount++;
            }
        }

        private void refreshvlcPlay()
        {
            //查询设备状态
            try
            {
                // 根据条件查询设备列表，如果条件为空，则表示查询所有
                DataSet ds = cameraVideoService.GetAllDevice(tbSearch.Text.Trim(), (this.currentPage-1)*screen,  screen);
                List<Device> devList = Global.TableToEntity<Device>(ds.Tables[0]);

                int size = devList.Count;

                // 遍历设备列表
                for (int i = 0; i < size; i++)
                {
                    Device dev = Global.GetDevice(i);
                    if(dev == null)
                    {
                        continue;
                    }

                    for(int n = 0; n < size; n++)
                    {
                        if(devList[n].Devid.Equals(dev.Devid))
                        {
                            if(devList[n].Status != dev.Status)
                            {
                                if (devList[n].Status == 0 && dev.Status != 0)
                                {
                                    vlcPlayer[i].Stop();
                                    string[] strArray = dev.Videowatchaddr.Split(':');
                                    vlcPlayer[i].LoadOnlineFile("udp://@:" + strArray[1]);
                                    pb[i].BackColor = Color.Black;
                                }
                                if (devList[n].Status == 2)
                                {
                                    pb[i].BackColor = Color.DarkRed;
                                }

                                Global.RemoveDevice(i);
                                Global.AddDevice(i, devList[n]);
                            }
                        }
                    }
                }

             }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        private void plView_MouseEnter(object sender, EventArgs e)
        {
            return;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void plView_Paint(object sender, PaintEventArgs e)
        {

        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x112)
            {
                switch ((int)m.WParam)
                {
                    //禁止双击标题栏关闭窗体  
                    case 0xF063:
                    case 0xF093:
                        m.WParam = IntPtr.Zero;
                        break;
                  
                    //禁止双击标题栏  
                    case 0xf122:
                        m.WParam = IntPtr.Zero;
                        break;
                   
                    //禁止最大化按钮  
                    case 0xf020:
                        m.WParam = IntPtr.Zero;
                        break;
                }
            }
            base.WndProc(ref m);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void plHead_Paint(object sender, PaintEventArgs e)
        {
            //e.Graphics.DrawRectangle(Pens.Red, 0, plHead.Height-2, plHead.Width, 2);
                        
        }

        /// <summary>
        /// 用户管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUserManage_Click(object sender, EventArgs e)
        {
            UserManageForm userManageForm = new UserManageForm();
            userManageForm.ShowDialog(this);
        }

        /// <summary>
        /// 系统管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSysManage_Click(object sender, EventArgs e)
        {
            SysManageForm sysManageForm = new SysManageForm();
            sysManageForm.ShowDialog(this);
        }

        /// <summary>
        /// 回放管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReview_Click(object sender, EventArgs e)
        {
            VideoReviewForm videoReviewForm = new VideoReviewForm();
            videoReviewForm.ShowDialog(this);
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CameraVideoForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dr = Global.showQuestionMessageBox("确定要退出系统吗",2);

            if (dr == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
            else
            {
                // 修改用户状态为离线
                UserService userService = new UserService();
                //string loginid = "";
                userService.UpdateUserStatus(Global.CurrentUser.LoginId, 0);
            }
        }

        /// <summary>
        /// 系统退出图标点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pbLogout_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 锁屏功能实现
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pbLock_Click(object sender, EventArgs e)
        {
            if (!isLocked)
            {
                isLocked = true;
                
                // 左侧树形菜单禁用
                tbControl.Enabled = false;

                // 顶部菜单栏禁用
                btnPreview.Enabled = false;
                btnReview.Enabled = false;
                btnUserManage.Enabled = false;
                btnSysManage.Enabled = false;
                pbLogout.Enabled = false;
                Image backImage = Resources.unlock;
                pbLock.Image = backImage;
                pbLock.Enabled = true;

                // 底部工具栏禁用
                plCenter.Enabled = false;
                plctr.Enabled = false;
            }
            else
            {
                LoginForm loginForm = new LoginForm();
                loginForm.Text = "解锁";
                if (loginForm.ShowDialog() == DialogResult.OK)
                {
                    isLocked = false;
                    // 左侧树形菜单禁用
                    tbControl.Enabled = true;

                    // 顶部菜单栏禁用
                    btnPreview.Enabled = true;
                    btnReview.Enabled = true;
                    btnUserManage.Enabled = true;
                    btnSysManage.Enabled = true;
                    pbLogout.Enabled = true;
                    Image backImage = Resources._lock;
                    pbLock.Image = backImage;
                    //pbLock.Enabled = true;

                    // 底部工具栏禁用
                    plCenter.Enabled = true;
                    plctr.Enabled = true;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlp_screen_SizeChanged(object sender, EventArgs e)
        {
            //split_screen(Global.configParam.ScreenNum);
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrePage_Click(object sender, EventArgs e)
        {
            try
            {
                this.DevTotal = cameraVideoService.GetDeviceCount(tbSearch.Text.Trim());
                GetTotalPage(this.DevTotal, screen);
                if (this.CurrentPage > 1)
                {
                    Global.ClearDevice();

                    InitDevCameraPanel(tbSearch.Text.Trim(), (currentPage - 2) * screen, screen);

                    this.CurrentPage--;
                }
                else if (this.CurrentPage == 1)
                {
                    Global.showAlertBox("已经是首页");
                }
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNextPage_Click(object sender, EventArgs e)
        {
            try
            {
                this.DevTotal = cameraVideoService.GetDeviceCount(tbSearch.Text.Trim());
                GetTotalPage(this.DevTotal, screen);
                if (this.CurrentPage < this.TotalPage)
                {
                    Global.ClearDevice();

                    InitDevCameraPanel(tbSearch.Text.Trim(), currentPage * screen, screen);

                    // 当前页加1
                    this.CurrentPage++;
                }
                else if (this.CurrentPage == this.TotalPage)
                {
                    // 已经是最后一页了
                    Global.showAlertBox("已经是最后一页");
                }
            }
            catch(Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFirst_Click(object sender, EventArgs e)
        {
            try
            {
                this.DevTotal = cameraVideoService.GetDeviceCount(tbSearch.Text.Trim());
                GetTotalPage(this.DevTotal, screen);
                if (this.CurrentPage == 1)
                {
                    Global.showAlertBox("已经是首页");
                    return;
                }

                Global.ClearDevice();

                InitDevCameraPanel(tbSearch.Text.Trim(), 0 * screen, screen);

                // 当前页加1
                this.CurrentPage = 1;
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 最后一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEndPage_Click(object sender, EventArgs e)
        {
            try
            {
                this.DevTotal = cameraVideoService.GetDeviceCount(tbSearch.Text.Trim());
                GetTotalPage(this.DevTotal, screen);
                if (this.CurrentPage == this.TotalPage)
                {
                    Global.showAlertBox("已经是最后一页");
                    return;
                }

                Global.ClearDevice();

                InitDevCameraPanel(tbSearch.Text.Trim(), currentPage * screen, screen);

                // 当前页加1
                this.CurrentPage = this.TotalPage;
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 全屏显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFullScreen_Click(object sender, EventArgs e)
        {
            if (!isBottomFullScreen)
            {
                isBottomFullScreen = true;
                this.FormBorderStyle = FormBorderStyle.None; //取消窗体边框
                splitContainerHead.Panel1Collapsed = true;
                splitContainer1.Panel1Collapsed = true;
                btnFullScreen.Text = "退出全屏";
                cbxScreenPage.Enabled = false;
            }
            else
            {
                isBottomFullScreen = false;
                this.FormBorderStyle = FormBorderStyle.FixedSingle;
                splitContainerHead.Panel1Collapsed = false;
                splitContainer1.Panel1Collapsed = false;
                btnFullScreen.Text = "全屏显示";
                cbxScreenPage.Enabled = true;
            }
        }

        /// <summary>
        /// 静音操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMute_Click(object sender, EventArgs e)
        {
            try
            {
                if (!isMute)
                {
                    vlcAudioPlayer0.SetMute(true);
                    vlcAudioPlayer1.SetMute(true);
                    isMute = true;
                    btnMute.Text = "取消静音";
                }
                else
                {
                    vlcAudioPlayer0.SetMute(false);
                    vlcAudioPlayer1.SetMute(false);
                    isMute = false;
                    btnMute.Text = "静音";
                }
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 动态切换分屏数目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxScreenPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = cbxScreenPage.SelectedIndex;
            screen = Global.SplitScreenNum(index);
            Global.ClearDevice();
            split_screen(screen);
            
            // 查询设备总数
            this.DevTotal = cameraVideoService.GetDeviceCount(tbSearch.Text.Trim());

            // 计算页数
            GetTotalPage(this.DevTotal, screen);

            InitDevCameraPanel(tbSearch.Text.Trim(),0, screen);
        }

         /// <summary>
         /// 暂时不用处理
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="e"></param>
        private void btnPreview_Click(object sender, EventArgs e)
        {

        }
    }
}
